package dataaccess

import (
	"GoServer/common"
	"GoServer/models"
	"GoServer/utils/databases"
	"context"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo/options"
	"strconv"
)

func SaveAnchorFinalScore(anchorId string, score uint64) error {
	coll := databases.MongoDB.Collection(common.GameName + models.AnchorCollection)
	filter := bson.M{"anchor_id": anchorId}
	update := bson.M{"$set": bson.M{"score": score}}
	_, err := coll.UpdateOne(context.TODO(), filter, update, mongoOptions(true))
	return err
}

// UnlockItemForAnchor 为指定主播解锁指定道具
// 使用 $addToSet 防止重复添加相同道具 ID
func UnlockItemForAnchor(anchorId, itemId string) error {
	itemUint, err := strconv.ParseUint(itemId, 10, 64)
	if err != nil {
		return err
	}

	coll := databases.MongoDB.Collection(common.GameName + models.AnchorCollection)
	filter := bson.M{"anchor_id": anchorId}
	update := bson.M{"$addToSet": bson.M{"unlock_item_id": uint(itemUint)}}

	_, err = coll.UpdateOne(context.TODO(), filter, update, mongoOptions(true))
	return err
}

func GetAnchorInfo(anchorId string) (*models.AnchorInfoBasic, error) {
	coll := databases.MongoDB.Collection(common.GameName + models.AnchorCollection)
	filter := bson.M{"anchor_id": anchorId}
	var info models.AnchorInfoBasic
	err := coll.FindOne(context.TODO(), filter).Decode(&info)
	if err != nil {
		return nil, err
	}
	return &info, nil
}

func mongoOptions(upsert bool) *options.UpdateOptions {
	opt := options.UpdateOptions{}
	opt.Upsert = &upsert
	return &opt
}
